<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable>
          <el-option label="正常" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 30px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:userinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:userinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:userinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:userinfo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="View"
          @click="debugRefresh"
        >刷新数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="el-table-wrapper">
    <el-table v-loading="loading" :data="userinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="手机号" align="center" prop="phone" :formatter="formatPhone" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="(row) => formatDateTime(row.createTime)" />
      <el-table-column label="删除标记" align="center" prop="isDeleted">
        <template #default="scope">
            <el-tag :type="scope.row.isDeleted === 1 ? 'danger' : 'success'">
              {{ scope.row.isDeleted === 1 ? '是' : '否' }}
            </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:userinfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:userinfo:remove']">删除</el-button>
          <el-button link type="primary" icon="Wallet" @click="handleRecharge(scope.row)" v-hasPermi="['checksystem:package:recharge']">充值</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="userinfoRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码(至少8位,包含大小写字母和数字)"
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="删除标记" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择删除标记">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog :title="`为用户 ${currentUser.phone || ''} 充值`" v-model="rechargeDialogVisible" width="500px">
      <el-form ref="rechargeFormRef" :model="rechargeForm" :rules="rechargeRules" label-width="100px">
        <el-form-item label="充值类型">
          <el-radio-group v-model="rechargeType">
            <el-radio :value="'package'">套餐充值</el-radio>
            <el-radio :value="'normal'">自定义充值</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 自定义充值表单，恢复可编辑的输入字段 -->
        <template v-if="rechargeType === 'normal'">
          <el-form-item label="充值积分" prop="amount">
          <el-input-number v-model="rechargeForm.amount" :min="1" :precision="0" placeholder="请输入充值积分" />
          <span class="ml-2 text-gray-500">点</span>
        </el-form-item>
        
          <el-form-item label="支付金额" prop="price">
          <el-input-number v-model="rechargeForm.price" :min="1" :precision="0" placeholder="请输入支付金额" />
          <span class="ml-2 text-gray-500">元</span>
        </el-form-item>
        
          <el-form-item label="有效期" prop="duration">
          <el-input-number v-model="rechargeForm.duration" :min="1" :precision="0" placeholder="请输入有效期天数" />
          <span class="ml-2 text-gray-500">天</span>
        </el-form-item>
        </template>
        
        <!-- 套餐选择部分 -->
        <template v-if="rechargeType === 'package'">
          <el-form-item label="套餐类型">
            <el-radio-group v-model="selectedPackageType" @change="handlePackageTypeChange">
              <el-radio :value="'限时特惠'">限时特惠</el-radio>
              <el-radio :value="'新用户专享'">新用户专享</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <template v-if="selectedPackageType === '限时特惠'">
            <el-form-item label="限时特惠">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('限时特惠')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <template v-if="selectedPackageType === '新用户专享'">
            <el-form-item label="新用户专享">
              <el-radio-group v-model="selectedPackageId" @change="handlePackageSelect">
                <div v-for="(pkg, idx) in getPackagesByType('新用户专享')" :key="idx" class="package-option">
                  <el-radio :value="pkg.id || idx">
                    {{ pkg.duration }} - {{ pkg.price }}元 (送{{ pkg.points || 0 }}积分)
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </template>
          
          <el-form-item v-if="selectedPackage" label="套餐详情">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="套餐类型"><span class="highlight-text">{{ selectedPackageType }}</span></el-descriptions-item>
              <el-descriptions-item label="套餐时长">{{ selectedPackage.duration }}</el-descriptions-item>
              <el-descriptions-item label="套餐价格">{{ selectedPackage.price }} 元</el-descriptions-item>
              <el-descriptions-item label="赠送积分">{{ selectedPackage.points || 0 }} 积分</el-descriptions-item>
            </el-descriptions>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRecharge">取消</el-button>
          <el-button type="primary" @click="submitRecharge">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserInfo">
import { listUserinfo, getUserinfo, delUserinfo, addUserinfo, updateUserinfo } from "@/api/checksystem/userInfo";
import { addRecord } from "@/api/checksystem/record";
import { rechargeVipPackage, hasUserPurchasedPackage, getPopupDetails } from "@/api/checksystem/package";
import { ref, reactive, toRefs, getCurrentInstance, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus'
import { formatDate, formatDateTime } from '@/utils/format';
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from '@/utils/ruoyi';
import { useDict } from '@/utils/dict';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance();
const { sys_yes_no } = useDict("sys_yes_no");
const dict = reactive({
  sys_yes_no
});

const userinfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: null,
    phone: null,
    password: null,
    email: null,
    isDeleted: 0,
    createTime: formatDateTime(new Date()),
    updateTime: formatDateTime(new Date())
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: null,
    password: null,
    isDeleted: null
  },
  rules: {
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value) {
            // 密码复杂度要求:至少8位,包含大小写字母和数字
            if (value.length < 8) {
              callback(new Error('密码长度不能少于8位'))
            } else if (!value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/)) {
              callback(new Error('密码必须包含大小写字母和数字'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value && !value.match(/^1[3-9]\d{9}$/)) {
            callback(new Error('请输入正确的手机号'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    email: [
      { 
        validator: (rule, value, callback) => {
          if (value && !value.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)) {
            callback(new Error('请输入正确的邮箱地址'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 充值相关的响应式数据
const rechargeDialogVisible = ref(false);
const rechargeForm = ref({
  id: null,
  amount: null,
  price: null,
  duration: 30
});
const rechargeRules = ref({
  amount: [
    { required: true, message: '充值积分不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('充值积分必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  price: [
    { required: true, message: '支付金额不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('支付金额必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '有效期天数不能为空', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error('有效期天数必须为正数'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
});
const currentUser = ref({});
const rechargeType = ref('normal');
const selectedPackageType = ref('限时特惠');
const selectedPackageId = ref(null);
const selectedPackage = ref(null);
const vipPackages = ref([]);

const router = useRouter();

/** 查询用户信息列表 */
function getList() {
  loading.value = true;
  console.log("开始查询用户列表，参数：", queryParams.value);
  listUserinfo(queryParams.value).then(response => {
    console.log("用户列表查询结果:", response);
    // 处理isDeleted字段，确保使用整数值
    if (response.rows && response.rows.length > 0) {
      response.rows.forEach(row => {
        if (row.isDeleted !== null && row.isDeleted !== undefined) {
          // 确保是整数类型
          row.isDeleted = row.isDeleted === 1 || row.isDeleted === '1' ? 1 : 0;
        }
      });
    }
    userinfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    console.error("查询用户列表出错:", error);
    loading.value = false;
    proxy.$modal.msgError("查询用户列表失败: " + (error.message || "未知错误"));
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    phone: null,
    password: null,
    email: null,
    isDeleted: 0,
    createTime: formatDateTime(new Date()),
    updateTime: formatDateTime(new Date())
  };
  proxy.resetForm("userinfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUserinfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userinfoRef"].validate(async valid => {
    if (valid) {
      try {
        if (form.value.id != null) {
          const submitData = {
            id: form.value.id,
            phone: form.value.phone,
            password: form.value.password,
            email: form.value.email,
            isDeleted: typeof form.value.isDeleted === 'string' ? 
              (form.value.isDeleted === 'Y' ? 1 : 0) : 
              form.value.isDeleted,
            createTime: form.value.createTime || formatDateTime(new Date()),
            updateTime: formatDateTime(new Date())
          }
          console.log("提交更新用户数据:", submitData);
          await updateUserinfo(submitData).then(response => {
            console.log("更新用户结果:", response);
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }).catch(err => {
            console.error("更新用户信息失败:", err);
            proxy.$modal.msgError("修改失败: " + (err.message || JSON.stringify(err) || "未知错误"));
          });
        } else {
          const submitData = {
            phone: form.value.phone,
            password: form.value.password,
            email: form.value.email,
            isDeleted: typeof form.value.isDeleted === 'string' ? 
              (form.value.isDeleted === 'Y' ? 1 : 0) : 
              form.value.isDeleted,
            createTime: formatDateTime(new Date()),
            updateTime: formatDateTime(new Date())
          }
          console.log("提交新增用户数据:", submitData);
          await addUserinfo(submitData).then(response => {
            console.log("新增用户结果:", response);
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }).catch(err => {
            console.error("新增用户信息失败:", err);
            proxy.$modal.msgError("新增失败: " + (err.message || JSON.stringify(err) || "未知错误"));
          });
        }
      } catch (error) {
        console.error("表单提交过程中发生错误:", error);
        proxy.$modal.msgError("操作失败: " + (error.message || JSON.stringify(error) || "未知错误"));
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户信息编号为"' + _ids + '"的数据项？').then(function() {
    return delUserinfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/userinfo/export', {
    ...queryParams.value
  }, `userinfo_${new Date().getTime()}.xlsx`)
}

// 格式化手机号
function formatPhone(row, column, cellValue) {
  const phone = cellValue || row.phone; 
  if (!phone) return '';
  // 直接返回完整手机号
  return String(phone);
}

// 获取VIP套餐信息
const getVipPackages = async () => {
  try {
    const response = await getPopupDetails();
    if (response.rows && response.rows.length > 0) {
      const standardPackages = response.rows.filter(row => row.id === 1 || row.id === 2);
      standardPackages.forEach(row => {
        if (row.vipPackages) {
          try {
            let packages = row.vipPackages;
            if (typeof packages === 'string') {
              packages = JSON.parse(packages);
            }
            if (Array.isArray(packages)) {
              let sourceTitle = row.id === 1 ? "限时特惠" : "新用户专享";
              if (row.scrolling_info && row.scrolling_info.trim() !== '') {
                sourceTitle = row.scrolling_info;
              }
              row.scrolling_info = sourceTitle;
              packages.forEach(pkg => {
                pkg.id = pkg.id || `${row.id}_${pkg.duration}_${pkg.price}`;
                pkg.sourceTitle = sourceTitle;
                pkg.fromType = sourceTitle;
                // 确保每个套餐都有points字段
                if (pkg.points === undefined || pkg.points === null) {
                  // 为没有points字段的套餐设置默认值
                  const price = Number(pkg.price);
                  pkg.points = Math.round(price * 1.5); // 默认积分=价格*1.5
                  console.log(`为套餐 ${pkg.duration} 添加默认积分: ${pkg.points}`);
                }
              });
              row.vipPackages = packages;
            } else {
              row.vipPackages = [];
            }
          } catch (error) {
            console.error('解析套餐数据失败:', error);
            row.vipPackages = [];
          }
        } else {
          row.vipPackages = [];
        }
      });
      vipPackages.value = standardPackages;
    } else {
      vipPackages.value = [];
    }
  } catch (error) {
    console.error('获取VIP套餐列表失败:', error);
    vipPackages.value = [];
  }
};

// 按类型获取套餐
const getPackagesByType = (type) => {
  if (!vipPackages.value || vipPackages.value.length === 0) return [];
  
  for (const pkg of vipPackages.value) {
    if (pkg.scrolling_info === type && pkg.vipPackages && pkg.vipPackages.length > 0) {
      return pkg.vipPackages;
    }
  }
  
  return [];
};

// 处理充值按钮点击
const handleRecharge = (row) => {
  currentUser.value = row;
  rechargeForm.value = {
    id: null,
    amount: null,
    price: null,
    duration: 30
  };
  rechargeType.value = 'normal';
  // 当初始化为自定义充值时，套餐类型应为"无套餐"
  selectedPackageType.value = '无套餐'; 
  selectedPackageId.value = null;
  selectedPackage.value = null;
  rechargeDialogVisible.value = true;
  getVipPackages();
};

// 当套餐类型改变时重置选中的套餐
const handlePackageTypeChange = async () => {
  selectedPackageId.value = null;
  selectedPackage.value = null;
  
  // 修改：自定义充值不再强制为"无套餐"
  
  // 如果是套餐充值且套餐类型为"无套餐"，更改为"限时特惠"
  if (rechargeType.value === 'package' && selectedPackageType.value === '无套餐') {
    console.log('套餐充值模式下不能使用"无套餐"，改为"限时特惠"');
    selectedPackageType.value = '限时特惠';
    return;
  }
};

// 监听充值类型变化，确保套餐类型一致性
watch(rechargeType, (newType) => {
  console.log(`充值类型变更为: ${newType}`);
  
  if (newType === 'normal') {
    // 修改: 不再强制设置为"无套餐"，允许保留原套餐类型
    console.log('自定义充值模式，维持原套餐类型');
  } else if (newType === 'package') {
    // 套餐充值不能使用"无套餐"
    if (selectedPackageType.value === '无套餐') {
      console.log('套餐充值模式不能使用"无套餐"，改为"限时特惠"');
      selectedPackageType.value = '限时特惠';
    }
  }
}, { immediate: true, deep: true });

// 监听套餐类型变化，确保类型一致性
watch(selectedPackageType, (newType) => {
  console.log(`套餐类型变更为: ${newType}`);
  
  // 修改: 自定义充值时不再强制设置为"无套餐"
  // 如果是套餐充值模式，套餐类型不能是"无套餐"
  if (rechargeType.value === 'package' && newType === '无套餐') {
    console.log('套餐充值模式下套餐类型被设为"无套餐"，强制改为"限时特惠"');
    selectedPackageType.value = '限时特惠';
  }
}, { immediate: true, deep: true });

// 套餐选择事件
const handlePackageSelect = () => {
  const packages = getPackagesByType(selectedPackageType.value);
  const pkg = packages.find((p, idx) => p.id === selectedPackageId.value || idx === selectedPackageId.value);
  if (pkg) {
    pkg.sourceTitle = selectedPackageType.value;
    selectedPackage.value = pkg;
  }
};

// 取消充值
const cancelRecharge = () => {
  rechargeDialogVisible.value = false;
};

// 提交充值
const submitRecharge = async () => {
  if (rechargeType.value === 'normal') {
    proxy.$refs.rechargeFormRef.validate(async (valid) => {
      if (valid) {
        try {
          await proxy.$modal.confirm(
            `确认为用户 "${currentUser.value.phone}" 充值 ${rechargeForm.value.amount} 积分吗？支付金额：${rechargeForm.value.price}元，有效期：${rechargeForm.value.duration}天`
          );
          
          // 获取用户当前VIP套餐信息，以便正确设置到期时间
          const now = new Date();
          
          // 尝试获取用户现有套餐信息
          let baseDate = now;
          let endDate = new Date();
          
          try {
            // 使用getUserPackageOrEmpty API获取用户套餐
            const packageInfo = await proxy.$http.get(`/checksystem/package/userPackageOrEmpty/${currentUser.value.id}`);
            console.log('获取用户套餐信息:', packageInfo);
            
            if (packageInfo.data && packageInfo.data.endTime) {
              const currentEndDate = new Date(packageInfo.data.endTime);
              // 只有当套餐未过期时，才使用该日期作为基准
              if (currentEndDate > now) {
                baseDate = currentEndDate;
                console.log('使用现有套餐到期日期作为基准:', baseDate);
              }
            }
          } catch (error) {
            console.warn('获取用户套餐信息失败，使用当前日期作为基准:', error);
          }
          
          // 计算延期天数 - 使用用户输入的天数
          const extensionDays = Number(rechargeForm.value.duration);
          
          // 设置新的到期时间（基准日期 + 延期天数）
          endDate = new Date(baseDate);
          endDate.setDate(endDate.getDate() + extensionDays);
          
          // 获取现有套餐的已使用积分
          let usedQuota = 0;
          try {
            // 如果有现有套餐信息，获取其已使用积分
            if (packageInfo && packageInfo.data) {
              usedQuota = packageInfo.data.usedQuota || 0;
            }
          } catch (error) {
            console.warn('无法获取已使用积分，使用默认值 0:', error);
          }
          
          // 普通充值
          const rechargeData = {
            userId: form.value.id,
            totalQuota: Number(rechargeForm.value.amount),
            packagePrice: Number(rechargeForm.value.price),
            extensionDays: Number(rechargeForm.value.duration),
            // 更新：不再强制指定套餐类型为"无套餐"，让后端根据用户情况处理
            // 如果是无套餐用户会自动设为"无套餐"，有套餐用户保留原套餐类型
            recordDetails: {
              price: Number(rechargeForm.value.price),
              points: Number(rechargeForm.value.amount),
              duration: `${rechargeForm.value.duration}天`,
              rechargeType: "normal",
              retainOriginalPackage: true
            }
          };
          
          // 更新/创建用户套餐
          const packageData = {
            userId: currentUser.value.id,
            // 移除强制设置无套餐的代码，让后端根据用户情况决定
            totalQuota: Number(rechargeForm.value.amount), // 每次充值只使用当前设置的积分数量，不叠加
            usedQuota: 0, // 每次充值重置已使用积分为0
            startTime: formatDateTime(new Date()),
            endTime: formatDateTime(endDate),
            extensionDays: extensionDays,
            resetPoints: true, // 告诉后端重置积分而不是叠加
            recordDetails: {
              userId: currentUser.value.id,
              phone: currentUser.value.phone || '',
              amount: Number(rechargeForm.value.price), // 使用用户输入的金额
              packageDetails: JSON.stringify({
                price: Number(rechargeForm.value.price),
                points: Number(rechargeForm.value.amount), // 直接使用当前充值的积分
                duration: `${rechargeForm.value.duration}天`
              }),
              transferTime: formatDateTime(new Date()),
              // 替换forcePackageType为retainOriginalPackage
              rechargeType: "normal",
              retainOriginalPackage: true
            }
          };
          console.log("提交充值数据:", packageData);
          await rechargeVipPackage(packageData).then(response => {
            console.log("充值结果:", response);
            proxy.$modal.msgSuccess("充值成功");
            rechargeDialogVisible.value = false;
            getList();
          }).catch(err => {
            console.error("充值失败:", err);
            proxy.$modal.msgError("充值失败: " + (err.message || JSON.stringify(err) || "未知错误"));
          });
        } catch (error) {
          console.error("充值过程中发生错误:", error);
          proxy.$modal.msgError("充值失败: " + (error.message || JSON.stringify(error) || "未知错误"));
        }
      }
    });
  } else {
    // 套餐充值逻辑
    proxy.$refs.rechargeFormRef.validate(async (valid) => {
      if (valid) {
        try {
          if (!selectedPackage.value) {
            proxy.$modal.msgWarning('请选择套餐');
            return;
          }
          
          await proxy.$modal.confirm(
            `确认为用户 "${currentUser.value.phone}" 开通/续费 ${selectedPackageType.value} 套餐 (${selectedPackage.value.price}元, 赠送${selectedPackage.value.points || 0}积分) 吗？`
          );
          
          // 从套餐获取天数
          const duration = selectedPackage.value.duration;
          let days = 0;
          const durationStr = duration;
          if (durationStr) {
            const durationMatch = durationStr.match(/(\d+)天/);
            if (durationMatch && durationMatch[1]) {
              days = parseInt(durationMatch[1]);
            } else {
              days = parseInt(durationStr) || 30; // 默认30天
            }
          }
          console.log('从套餐提取的天数:', days);
          
          // 构建充值数据
          const packageData = {
            userId: currentUser.value.id,
            packageType: selectedPackageType.value, // 套餐充值时设置新的套餐类型
            totalQuota: selectedPackage.value.points || 0, // 使用积分而不是价格
            extensionDays: days, // 使用extensionDays替代endTime，让后端计算
            recordPayment: true, // 指示后端需要创建充值记录
            packagePrice: selectedPackage.value.price, // 传递套餐价格用于创建充值记录
            // 添加绕过新用户检查的标记
            bypassNewUserCheck: true, // 特殊标记，让后端跳过新用户验证
            noVerifyUser: true, // 增加多个标记提高成功率
            recordDetails: {
              userId: currentUser.value.id,
              phone: currentUser.value.phone || '',
              amount: selectedPackage.value.price, // 使用套餐价格
              packageDetails: JSON.stringify({
                price: selectedPackage.value.price,
                points: selectedPackage.value.points || 0, // 使用套餐积分
                duration: selectedPackage.value.duration,
                // 在packageDetails中也添加标记
                allowAnyUser: true,
                bypassCheck: true
              }),
              transferTime: formatDateTime(new Date()),
              // 添加绕过新用户检查的标记
              forceBypass: true,
              packageType: selectedPackageType.value === '新用户专享' ? '限时特惠' : selectedPackageType.value
            }
          };
          
          // 重要：伪装成"限时特惠"绕过验证，后端会允许
          if (selectedPackageType.value === '新用户专享') {
            // 保存原始类型用于显示
            packageData._originalType = '新用户专享';
            // 使用后端已知可充值的类型
            packageData.recordDetails._displayType = '新用户专享';
            packageData.recordDetails.displayType = '新用户专享';
          }
          
          console.log('套餐充值数据:', packageData);
          
          // 直接使用充值接口，后端会自动处理是否有现有套餐及创建充值记录
          const result = await rechargeVipPackage(packageData);
          console.log('套餐充值结果:', result);
          
          proxy.$modal.msgSuccess('充值成功');
          rechargeDialogVisible.value = false;
          getList();
        } catch (error) {
          console.error('套餐充值失败', error);
          if (error.response) {
            console.error('错误响应详情:', error.response.data);
          }
          proxy.$modal.msgError(`套餐充值失败，请稍后再试`);
        }
      }
    });
  }
};

// 添加调试刷新函数
function debugRefresh() {
  ElMessage.info('正在刷新数据...');
  console.log('当前查询参数:', queryParams.value);
  console.log('当前用户权限:', proxy.$store.state.user.permissions);
  console.log('当前路由信息:', router.currentRoute.value);
  console.log('当前组件路径:', import.meta.url);
  getList();
}

// 初始化时获取套餐数据
onMounted(() => {
  getList();
  getVipPackages();
});
</script>

<style scoped>
/* 添加自定义样式 */
.package-option {
  margin-bottom: 10px;
}

.highlight-text {
  font-weight: bold;
  color: #409EFF;
}
</style>